package com.rh.bmw4s.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rh.bmw4s.R;
import com.rh.bmw4s.bean.LogOutBean;
import com.rh.bmw4s.bean.QianDaoBean;
import com.rh.bmw4s.bean.UserInfoBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.ui.ComplainActivity;
import com.rh.bmw4s.ui.LoginRegActivity;
import com.rh.bmw4s.ui.PersonalDataActivity;
import com.rh.bmw4s.ui.WebShowActivity;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.rh.bmw4s.utills.glide.GlideImageLoader;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 个人中心界面
 */

public class FiveFragment extends Fragment {

    @BindView(R.id.img_center_header)
    ImageView imgHeader;
    @BindView(R.id.btn_center_qiandao)
    TextView btnQiandao;
    @BindView(R.id.tv_center_nick)
    TextView tvNick;
    @BindView(R.id.tv_center_integral)
    TextView tvIntegral;                //积分
    @BindView(R.id.tv_center_info)
    TextView tvInfo;
    @BindView(R.id.ll_center_info)
    LinearLayout llCenterInfo;
    @BindView(R.id.tv_center_car)
    TextView tvMyCar;
    @BindView(R.id.ll_center_car)
    LinearLayout llCenterCar;
    @BindView(R.id.tv_center_news)
    TextView tvNews;
    @BindView(R.id.ll_center_news)
    LinearLayout llCenterNews;
    @BindView(R.id.tv_center_collect)
    TextView tvCollect;
    @BindView(R.id.ll_center_collect)
    LinearLayout llCenterCollect;
    @BindView(R.id.tv_center_changepsw)
    TextView tvChangepsw;
    @BindView(R.id.ll_center_changepsw)
    LinearLayout llCenterChangepsw;
    @BindView(R.id.tv_center_exit)
    TextView tvExit;
    @BindView(R.id.ll_center_exit)
    LinearLayout llCenterExit;
    Unbinder unbinder;
    @BindView(R.id.img_center_tousu)
    TextView imgTousu;

    private Gson gson;
    private GlideImageLoader imageLoader;
    private int userId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_5, container, false);
        unbinder = ButterKnife.bind(this, view);
        gson = new Gson();
        imageLoader = new GlideImageLoader(getActivity());
        userId = SPUtils.getInstance().getInt(ConfigValue.userId);

        getUserInfo();

        //本地广播，当用户修改信息后回来刷新
        receiveAdDownload();
        return view;
    }


    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        OkGo.<String>post(Constant.UserInfo)
                .tag(getActivity())
                .params("user_id", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UserInfoBean infoBean = gson.fromJson(response.body().toString(), UserInfoBean.class);
                        if (infoBean.getStatus() == Constant.SUCESS) {
                            UserInfoBean.DatasBean bean = infoBean.getDatas();
                            tvNick.setText(bean.getUsername());
                            tvIntegral.setText("积分: " + bean.getSign());   //积分
                            imageLoader.displayCircle(bean.getLogo(), 3, getActivity().getResources().getColor(R.color.white), imgHeader);

                            //保存用户信息
                            SPUtils.getInstance().put(ConfigValue.nick, bean.getUsername());
                            SPUtils.getInstance().put(ConfigValue.relName, bean.getRelname());
                            SPUtils.getInstance().put(ConfigValue.headUrl, bean.getLogo());
                            SPUtils.getInstance().put(ConfigValue.gender, bean.getGender());
                            SPUtils.getInstance().put(ConfigValue.sign, bean.getSign());
                            SPUtils.getInstance().put(ConfigValue.telPhone, bean.getTel());
                        } else {
                            ToastUtils.toastForShort(getActivity(), "请求信息失败");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(), "请求用户信息失败");
                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.img_center_tousu, R.id.btn_center_qiandao, R.id.ll_center_info, R.id.ll_center_car, R.id.ll_center_news,
            R.id.ll_center_collect, R.id.ll_center_changepsw, R.id.ll_center_exit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_center_tousu:        //投诉
                Intent intent = new Intent(getActivity(), ComplainActivity.class);
                //intent.putExtra("url", "http://4s.liexianghudong.com/home/index/suggest/id/" + userId);
                startActivity(intent);
                break;
            case R.id.btn_center_qiandao:     //签到
                beginQiandao();
                //startActivity(new Intent(getActivity(), SelectCarTypeActivity.class));
                break;
            case R.id.ll_center_info:          //个人信息
                startActivity(new Intent(getActivity(), PersonalDataActivity.class));
                break;
            case R.id.ll_center_car:
                //http://4s.liexianghudong.com/home/index/carmanage/id/20
                Intent intent1 = new Intent(getActivity(), WebShowActivity.class);
                intent1.putExtra("url", Constant.H5CARMANAGE + userId);
                startActivity(intent1);
                break;
            case R.id.ll_center_news:
                Intent intent2 = new Intent(getActivity(), WebShowActivity.class);
                intent2.putExtra("url", Constant.H5NEWS + userId);
                startActivity(intent2);
                break;
            case R.id.ll_center_collect:
                Intent intent3 = new Intent(getActivity(), WebShowActivity.class);
                intent3.putExtra("url", Constant.H5COLLECT + userId);
                startActivity(intent3);
                break;
            case R.id.ll_center_changepsw:
                Intent intent4 = new Intent(getActivity(), WebShowActivity.class);
                intent4.putExtra("url", Constant.H5CHANGEPSW + userId);
                startActivity(intent4);
                break;
            case R.id.ll_center_exit:
                logOut();
                break;
        }
    }

    /**
     * 退出登录l
     */
    private void logOut() {
        OkGo.<String>post(Constant.LogOut)
                .tag(getActivity())
                .params("user_id", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d(response.body().toString());
                        LogOutBean logOutBean = gson.fromJson(response.body().toString(), LogOutBean.class);
                        if (logOutBean.getStatus() == Constant.SUCESS) {
                            SPUtils.getInstance().put(ConfigValue.userId, 0);
                            ToastUtils.toastForShort(getActivity(), "退出成功");
                            startActivity(new Intent(getActivity(), LoginRegActivity.class));
                            getActivity().finish();
                        } else {
                            ToastUtils.toastForShort(getActivity(), logOutBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(), "退出登录失败");
                    }
                });
    }

    /**
     * 签到
     */
    private void beginQiandao() {
        OkGo.<String>post(Constant.QianDao)
                .tag(getActivity())
                .params("user_id", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d(userId);
                        LogUtils.d(response.body().toString());
                        QianDaoBean qianDaoBean = gson.fromJson(response.body().toString(), QianDaoBean.class);
                        if (qianDaoBean.getStatus() == Constant.SUCESS) {
                            ToastUtils.toastForShort(getActivity(), "签到成功了");
                            tvIntegral.setText("积分: " + qianDaoBean.getDatas().getSign());
                        } else {
                            ToastUtils.toastForShort(getActivity(), qianDaoBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        // LogUtils.d(response.body().toString());
                        LogUtils.d(userId);
                        ToastUtils.toastForShort(getActivity(), "签到失败");
                    }
                });
    }


    LocalBroadcastManager broadcastManager;

    /**
     * 注册广播接收器
     */
    private void receiveAdDownload() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("refreshinfo");
        broadcastManager.registerReceiver(mAdDownLoadReceiver, intentFilter);
    }

    BroadcastReceiver mAdDownLoadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");
            if (TextUtils.equals("1", result)) {
                getUserInfo();
            }
        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        boolean aBoolean = SPUtils.getInstance().getBoolean(ConfigValue.isOpenEvents);
        if (!hidden && aBoolean) {
            getUserInfo();
            SPUtils.getInstance().put(ConfigValue.isOpenEvents, false);
        }
    }
}
